<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace process;

use app\common\ApiStatus;
use app\common\TaskStatus;
use app\service\MongodbService;
use support\Log;
use Workerman\Connection\TcpConnection;

class Webtcp
{
    public function onMessage(TcpConnection $connection, $data)
    {
        $_ret  = ['code' => ApiStatus::API_ERROR->value, 'msg' => 'error'];
        $_data = json_decode($data, true);
        if (!is_array($_data)) return $connection->send(json_encode($_ret));
        $code = $_data['code'] ?? '';
        if (empty($code)) {
            $_ret = ['code' => ApiStatus::API_ERROR->value, 'msg' => 'error:task_code'];
            return $connection->send(json_encode($_ret));
        }
        switch ($code) {
            case 'task_completed':
                $_rs = $_data['data'] ?? null;
                if (empty($_rs)) return $connection->send(json_encode($_ret));
                $file_size = 0;
                foreach ($_rs['files'] as $value) {
                    $file_size += $value['size'];
                }
                $id       = $_rs['id'];
                $msg      = $_rs['msg'] ?? '';
                $files    = $_rs['files'] ?? [];
                $ext_tags = [];
                foreach ($files as $va) {
                    $name       = $va['name'];
                    $ex_name    = explode('.', $name);
                    $ext_tags[] = end($ex_name);
                }
                $u_data = [
                    'completed_files' => $_rs['files'],
                    'status'          => $_rs['result'] == 1 ? TaskStatus::TASK_SUCCESS->value : TaskStatus::TASK_FAILED->value,
                    'msg'             => $msg, 'file_size' => $file_size, 'ext_tags' => $ext_tags,
                ];
                MongodbService::instance()->initDb()->_update(['id' => $id], $u_data);
                $_ret = $_data;
                Log::info(date('Y-m-d H:i:s') . "\ntask_completed:\n" . $data . PHP_EOL);
                break;
            default:
                break;
        }
        $connection->send(json_encode($_ret, JSON_UNESCAPED_UNICODE));
    }

}
